package com.d3works.studio.db.repo;

import com.d3works.exception.D3worksException;
import com.d3works.meta.db.MetaView;
import com.d3works.meta.db.repo.MetaViewRepository;
import com.d3works.studio.db.ChartBuilder;
import com.d3works.studio.service.builder.ChartBuilderService;
import com.google.inject.Inject;
import java.util.List;
import javax.validation.ValidationException;
import javax.xml.bind.JAXBException;

public class ChartBuilderRepo extends ChartBuilderRepository {

  @Inject private MetaViewRepository metaViewRepo;

  @Inject private ChartBuilderService chartBuilderService;

  @Override
  public ChartBuilder save(ChartBuilder chartBuilder) throws ValidationException {

    try {
      chartBuilderService.build(chartBuilder);
    } catch (D3worksException | JAXBException e) {
      // refresh(chartBuilder);
      throw new ValidationException(e);
    }

    return super.save(chartBuilder);
  }

  @Override
  public void remove(ChartBuilder chartBuilder) {

    MetaView metaView = chartBuilder.getMetaViewGenerated();
    List<ChartBuilder> chartBuilders =
        all()
            .filter("self.metaViewGenerated = ?1 and self.id != ?2", metaView, chartBuilder.getId())
            .fetch();
    for (ChartBuilder builder : chartBuilders) {
      builder.setMetaViewGenerated(null);
    }

    if (metaView != null) {
      metaViewRepo.remove(metaView);
    }

    super.remove(chartBuilder);
  }
}
